#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//#define	NDEBUG
#include <assert.h>

#define RANDOM(min, max)	(rand() % ((max) - (min) + 1) + (min))

int init_grid_data(const char *f_name, int height, int width, int iteration)
{
	
	FILE *fp;
	int i, j;
	char *txt_buf;
	int txt_cnt;

	txt_buf = (char *) malloc(sizeof(char) * (height + 2) * (width * 2 + 1));
	
	fp = fopen(f_name, "wb");

	srand(1); 
	//srand(time(NULL)); 

	txt_cnt = 0;
	txt_cnt += sprintf(txt_buf + txt_cnt, "%d %d\n", height, width);
	txt_cnt += sprintf(txt_buf + txt_cnt, "%d\n", iteration);
	for (i = 0; i < height; i++) {
		for (j = 0; j < width; j++) {
			*(txt_buf + txt_cnt) = RANDOM(0, 1) + '0';
			txt_cnt++;
			*(txt_buf + txt_cnt) = ' ';
			txt_cnt++;
		}
		*(txt_buf + txt_cnt) = '\n';
		txt_cnt++;
	}
	fwrite(txt_buf, sizeof(char), txt_cnt, fp);

	fclose(fp);
	free(txt_buf);
	return 0;
}

int main(int argc, char *argv[])
{
	int height, width, iteration;

	if (argc < 5) { 
		// if you don't specify the name of the source and destination file
		printf("Error: too few arguments.\n");
		return 1;
	} else { //read the file you specified
		height = atoi(argv[2]);
		width = atoi(argv[3]);
		iteration = atoi(argv[4]);
		printf("height: %d width: %d iter : %d\n", height, width, iteration);
		init_grid_data(argv[1], height, width, iteration);
	}

	return 0;
}
